﻿using System;
using System.Collections.Generic;

namespace YummyGame.Framework
{
    public class BaseBuilder
    {
        protected float ParseFloat(SkillDescriptorField field, string key, float def = 0.0f)
        {
            var child = field.GetChildField(key);
            if (child == null || !child.IsNumber()) return def;
            return child.AsNumber();
        }

        protected string ParseString(SkillDescriptorField field, string key, string def = "")
        {
            var child = field.GetChildField(key);
            if (child == null || !child.IsString()) return def;
            return child.AsString();
        }

        protected Expression ParseExpression(SkillDescriptorField field, string key)
        {
            var child = field.GetChildField(key);
            if (child == null) return ExpressionConst.Zero;
            if (child.IsNumber()) return new ExpressionConst(child.AsNumber());
            else if (child.IsString()) return new ExpressionParser().Parse(child.AsString());
            else return ExpressionConst.Zero;
        }

        protected SkillActionPrototype ParseChildAction(SkillDescriptorField field, string key)
        {
            var child = field.GetChildField(key);
            if (child == null || !child.IsStruct()) return null;
            var action = new SkillRootPrototype();
            foreach (var c in child.pairs)
            {
                var childName = c.key;
                string typeName = "YummyGame.Framework.ActionBuilder_" + childName;
                Type type = Type.GetType(typeName);
                if (type == null) continue;
                ActionBuilder build = (ActionBuilder)Activator.CreateInstance(type);
                action.AddChild(build.Build(c.field));
            }
            return action;
        }
    }
}
